package com.wyt.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;

@Component("wytBeanPostProcessor")
public class WytBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessorBeforeInitialization(Object bean, String beanName) {
        if(Objects.equals(beanName,"userService")){
            //如果是,我们把它的aopName填充
            ((UserServiceImpl)bean).setAopName("before赋值");
        }
        return bean;
    }

    @Override
    public Object postProcessorAfterInitialization(Object bean, String beanName) {
        if(Objects.equals(beanName,"userService")){
            //如果是,我们把它的aopName填充
            ((UserServiceImpl)bean).setAopName("after赋值");

            //JDK动态代理,实现aop
            Object proxyInstance = Proxy.newProxyInstance(WytBeanPostProcessor.class.getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("aop逻辑");
                            return method.invoke(bean, args);
                        }
                    });
            return proxyInstance;
        }
        return bean;
    }
}
